package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.domain.po.Clazz;
import com.itheima.domain.query.ClazzQueryParam;
import com.itheima.domain.vo.PageResult;
import com.itheima.mapper.ClazzMapper;
import com.itheima.service.ClazzService;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.List;

@Service
public class ClazzServiceImpl extends ServiceImpl<ClazzMapper, Clazz> implements ClazzService {

    /**
     * 分页查询班级信息
     *
     * @param clazz 查询参数
     * @return 分页结果
     */
    @Override
    public PageResult<Clazz> pageClazz(ClazzQueryParam clazz) {
        //1-参数校验：分页参数
        Integer pageNum = clazz.getPage();
        Integer pageSize = clazz.getPageSize();
        if (ObjectUtils.isNull(pageNum) || ObjectUtils.isNull(pageSize)) {
            throw new RuntimeException("pageNum or pageSize is null");
        }
        Page<Clazz> page = Page.of(pageNum, pageSize);
        this.getBaseMapper().selectClazzPage(page, clazz);
        List<Clazz> records = page.getRecords();
        if (CollectionUtils.isNotEmpty(records)) {
            records.forEach(cl -> {
                String status = "";
                LocalDate beginDate = cl.getBeginDate();
                LocalDate endDate = cl.getEndDate();
                if (beginDate != null && endDate != null) {
                    if (LocalDate.now().isAfter(beginDate) && LocalDate.now().isBefore(endDate)) {
                        status = "进行中";
                    } else if (LocalDate.now().isBefore(beginDate)) {
                        status = "未开始";
                    } else {
                        status = "已结束";
                    }
                }
                cl.setStatus(status);
            });
        }
        return PageResult.<Clazz>builder().total(page.getTotal()).rows(records).build();

    }
}
